﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;

namespace test.XcoAppSpaces.Transport.Sockets.Auth
{
	class ConnectedTcpClientPair : IDisposable
	{
		private int port = 9001;
		//public int Port2 = 9002;

		//private TcpListener listener;

		public TcpClient ReceivingClient;
		public TcpClient SendingClient;

		public ConnectedTcpClientPair()
		{
			var listener = new TcpListener(IPAddress.Any, port);
			listener.Start();
			var task = Task.Factory.StartNew(() =>
				{
					ReceivingClient = listener.AcceptTcpClient();
					listener.Stop();
				});
			Thread.Sleep(100);
			SendingClient = new TcpClient("localhost", port);
			task.Wait();
		}

		public void Dispose()
		{
			if (ReceivingClient.Client != null)
				ReceivingClient.Client.Close();
			ReceivingClient.Close();

			if (SendingClient.Client != null)
				SendingClient.Client.Close();
			SendingClient.Close();
		}
	}

	static class TcpClientExtensions
	{
		public static ConnectionInfo GetConnectionInfo(this TcpClient client)
		{
			return new ConnectionInfo { Client = client, Stream = client.GetStream() };
		}
	}
}
